/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.infor.web;

import java.text.NumberFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.fee.entity.Js;
import com.jeeplus.modules.fee.entity.RecivedDetil;
import com.jeeplus.modules.infor.entity.RentDetil;
import com.jeeplus.modules.infor.entity.RentjsDetil;
import com.jeeplus.modules.infor.entity.StoreBudget;
import com.jeeplus.modules.infor.service.RentDetilService;
import com.jeeplus.modules.infor.service.RentjsDetilService;
import com.jeeplus.modules.infor.service.StoreBudgetService;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.infor.entity.RentJs;
import com.jeeplus.modules.infor.service.RentJsService;

/**
 * 仓租结算单Controller
 * @author 李超辉
 * @version 2018-09-28
 */
@Controller
@RequestMapping(value = "${adminPath}/infor/rentJs")
public class RentJsController extends BaseController {

	@Autowired
	private RentJsService rentJsService;
	@Autowired
	private RentDetilService rentDetilService;
	@Autowired
	private RentjsDetilService rentjsDetilService;
	@Autowired
	private StoreBudgetService setStatus;
	
	@ModelAttribute
	public RentJs get(@RequestParam(required=false) String id) {
		RentJs entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = rentJsService.get(id);
		}
		if (entity == null){
			entity = new RentJs();
		}
		return entity;
	}
	
	/**
	 * 仓租结算单列表页面
	 */
	@RequiresPermissions("infor:rentJs:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/infor/rentJsList";
	}
	/**
	 * 仓租结算单列表页面
	 */
	@RequestMapping(value = {"list1"})
	public String list1() {
		return "modules/infor/4/rentJsList";
	}
	/**
	 * 获取核销明细
	 */
	@ResponseBody
	@RequestMapping(value = "getdetil")
	public String getdetil(String i, RedirectAttributes redirectAttributes) {
		RentjsDetil recivedDetil=new RentjsDetil();
		recivedDetil.setPid(i);
		List<RentjsDetil> l=rentjsDetilService.findList(recivedDetil);
		Gson g=new Gson();
		return g.toJson(l).toString();
	}

	/**
	 * 取消核销
	 */
	@ResponseBody
	@RequestMapping(value = "qdqx")
	public String qdqx(String idd, RedirectAttributes redirectAttributes) {
		String[] ids=idd.split(",");
		for(String i:ids){
			RentjsDetil recivedDetil=rentjsDetilService.get(i);
			NumberFormat nf = NumberFormat.getInstance();
			RentJs js=rentJsService.get(recivedDetil.getPid());
			Double d=Double.parseDouble(recivedDetil.getMoney());
			Double e=Double.parseDouble(js.getHx().replace(",",""));
			Double f=Double.parseDouble(js.getWhx().replace(",",""));
			js.setHx(nf.format(e-d).replaceAll(",",""));
			js.setWhx(nf.format(f+d).replaceAll(",",""));
			if(js.getWhx().equals("0.0")||js.getWhx().equals("0")){
				js.setStatus("已核销");
			}else if(js.getHx().equals("0")||js.getHx().equals("0.0")){
				js.setStatus("已创建");
			}else{

				js.setStatus("部分核销");
			}
			rentJsService.save(js);
			rentjsDetilService.delete(recivedDetil);}
		return "";
	}

	/**
	 * 仓租结算单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("infor:rentJs:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(RentJs rentJs, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			rentJs.setPro(pro);
		}
		Page<RentJs> page = rentJsService.findPage(new Page<RentJs>(request, response), rentJs);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑仓租结算单表单页面
	 */
	@RequiresPermissions(value={"infor:rentJs:view","infor:rentJs:add","infor:rentJs:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(RentJs rentJs, Model model) {
		model.addAttribute("rentJs", rentJs);
		RentjsDetil rent=new RentjsDetil();
		rent.setPid(rentJs.getId());
		List<RentjsDetil> lisyt=rentjsDetilService.findList(rent);
		model.addAttribute("list",lisyt);
		return "modules/infor/rentJsForm";
	}

	/**
	 * 查看，增加，编辑仓租结算单表单页面
	 */
	@RequestMapping(value = "form1")
	public String form1(RentJs rentJs,String je,String i, Model model) {
		rentJs.setDate(new Date());
		rentJs.setStatus("已创建");
		rentJs.setCid(i);
		rentJs.setKpje(je);
		rentJs.setHx("0");
		rentJs.setWhx(je);
		model.addAttribute("rentJs", rentJs);
		if(!UserUtils.getUseroffice().equals("总部")){
			rentJs.setPro(UserUtils.getUseroffice());
		}
		return "modules/infor/3/rentJsForm";
	}

	/**
	 * 保存仓租结算单
	 */
	@ResponseBody
	@RequiresPermissions(value={"infor:rentJs:add","infor:rentJs:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(RentJs rentJs, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, rentJs)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		if(rentJs.getIsNewRecord()){
           String i=rentJs.getCid();
           String[] ids=i.split(",");
           for(String id:ids){
			   StoreBudget s=setStatus.get(id);
          s.setKpzt("已开票");
          s.setKpje(s.getZsr());
          s.setKprq(rentJs.getDate());
          s.setFph(rentJs.getFph());
          s.setDzje("0");
			   setStatus.save(s);
		   }
		}
		rentJsService.save(rentJs);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存仓租结算单成功");
		return j;
	}
	
	/**
	 * 删除仓租结算单
	 */
	@ResponseBody
	@RequiresPermissions("infor:rentJs:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(RentJs rentJs, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		rentJsService.delete(rentJs);
		j.setMsg("删除仓租结算单成功");
		return j;
	}
	
	/**
	 * 批量删除仓租结算单
	 */
	@ResponseBody
	@RequiresPermissions("infor:rentJs:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			rentJsService.delete(rentJsService.get(id));
		}
		j.setMsg("删除仓租结算单成功");
		return j;
	}


	/**
	 * 取消开票
	 */
	@ResponseBody
	@RequestMapping(value = "qxkp")
	public AjaxJson qxkp(RentJs rentJs,RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
       String i=rentJs.getCid();
       String[] ids=i.split(",");
       for(String id:ids){
		   StoreBudget s=setStatus.get(id);
		   s.setKpzt("未开票");
		   setStatus.save(s);
       }
       rentJsService.delete(rentJs);
		j.setMsg("取消开票成功");
		return j;
	}

	/**
	 * 核销
	 */
	@ResponseBody
	@RequestMapping(value = "hx")
	public AjaxJson hx(RentJs rentJs,String je,String person,Date date,String type,String fee,String remarks) {
		AjaxJson j = new AjaxJson();
		RentjsDetil detil=new RentjsDetil();
		detil.setPid(rentJs.getId());
		detil.setDate(date);
		detil.setPerson(person);
		detil.setFee(fee);
		detil.setMoney(je);
		detil.setType(type);
		detil.setRemarks(remarks);
		rentjsDetilService.save(detil);
		String ids=rentJs.getCid();
		String kpje=rentJs.getKpje();
		String[] idd=ids.split(",");
		for(String id:idd){
			StoreBudget sb=setStatus.get(id);
			String kp=sb.getKpje();
			String dz=sb.getDzje();
			double dzje=Double.parseDouble(je)/Double.parseDouble(kpje)*Double.parseDouble(kp);
			double ndz=Double.parseDouble(dz)+dzje;
			sb.setDzje(ndz+"");
			setStatus.save(sb);
		}
        double hxje=Double.parseDouble(je)+Double.parseDouble(rentJs.getHx());
        double whx=Double.parseDouble(rentJs.getWhx())-Double.parseDouble(je);
		NumberFormat nf = NumberFormat.getInstance();
		rentJs.setWhx(nf.format(whx).replaceAll(",",""));
		rentJs.setHx(nf.format(hxje).replaceAll(",",""));
		if(Double.parseDouble(rentJs.getKpje())==hxje){
			rentJs.setStatus("已核销");
		}else{
			rentJs.setStatus("部分核销");
		}
		rentJsService.save(rentJs);
		j.setMsg("核销成功");
		return j;
	}

	/**
	 * 核销
	 */
	@ResponseBody
	@RequestMapping(value = "qxhx")
	public AjaxJson qxhx(RentJs rentJs) {
		AjaxJson j = new AjaxJson();
		rentJs.setWhx(rentJs.getKpje());
		rentJs.setHx("0");
		rentJs.setStatus("已创建");
		rentJsService.save(rentJs);
		RentjsDetil r=new RentjsDetil();
		r.setPid(rentJs.getId());
		List<RentjsDetil> list=rentjsDetilService.findList(r);
		for(RentjsDetil re:list){
			rentjsDetilService.delete(re);
		}

		j.setMsg("取消核销成功");
		return j;
	}
	/**
	 * 核销
	 */
	@ResponseBody
	@RequestMapping(value = "gz")
	public AjaxJson gz(RentJs rentJs) {
		AjaxJson j = new AjaxJson();
		rentJs.setStatus("已关账");
		rentJsService.save(rentJs);
		j.setMsg("关账成功");
		return j;
	}
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("infor:rentJs:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(RentJs rentJs, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "仓租结算单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<RentJs> page = rentJsService.findPage(new Page<RentJs>(request, response, -1), rentJs);
    		new ExportExcel("仓租结算单", RentJs.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出仓租结算单记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("infor:rentJs:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<RentJs> list = ei.getDataList(RentJs.class);
			for (RentJs rentJs : list){
				try{
					rentJsService.save(rentJs);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条仓租结算单记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条仓租结算单记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入仓租结算单失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/rentJs/?repage";
    }
	
	/**
	 * 下载导入仓租结算单数据模板
	 */
	@RequiresPermissions("infor:rentJs:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "仓租结算单数据导入模板.xlsx";
    		List<RentJs> list = Lists.newArrayList(); 
    		new ExportExcel("仓租结算单数据", RentJs.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/rentJs/?repage";
    }

}